//
//  CYNavigationVController.m
//  CreditAddressBook
//
//  Created by Lee on 15/4/22.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYNavigationVController.h"
#import "LEBarButtonItem.h"
#import "CYBackBarButtonItem.h"
#import "UIViewController+LEBackButtonHandler.h"
#import "badge.h"

@interface CYNavigationVController ()<UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIVisualEffectView *visualEffectView;

@end

@implementation CYNavigationVController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNaviBarItem];
    [self setupPopGestureRecognizer];
}

- (void)setupNaviBarItem {
     
    UINavigationBar *naviBar = [UINavigationBar appearance];//得到所有导航栏
//    [naviBar setBackgroundImage:[UIImage imageWithColor:CYNaviThemeColorWithAlpha(0.996)] forBarMetrics:UIBarMetricsDefault];
     
     
     
    naviBar.barTintColor = CYNaviThemeColor;//
    [naviBar setTintColor:CYNaviTitleColor];//设置导航栏所有字体的颜色
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = CYNaviTitleColor;
    textAttrs[NSFontAttributeName] = CYNaviFont;
    [naviBar setTitleTextAttributes:textAttrs];
    
    //设置返回按钮的字体颜色，首先在plist中加入View controller-based status bar appearance为NO
//    naviBar.barStyle = UIStatusBarStyleLightContent;
//    naviBar.translucent = NO;
//    naviBar.backIndicatorImage = [UIImage imageNamed:@"back_25"];
//    naviBar.backIndicatorTransitionMaskImage = [UIImage imageNamed:@"back_25"];
    
    UIBarButtonItem *barButtonItem = [UIBarButtonItem appearance];
//    [barButtonItem setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];//将返回按钮的文字position设置不在屏幕上显示
    //设置返回按钮图片
    UIImage *backImage = [UIImage imageNamed:@"backItemImage_white"];
    [barButtonItem setBackButtonBackgroundImage:[backImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, backImage.size.width, 0, 0)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
//    [barButtonItem setBackButtonTitlePositionAdjustment:UIOffsetMake(-233, 0) forBarMetrics:UIBarMetricsDefault];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];//设置状态栏为白色
    
//    [self transitionFromCustomNavigationBarToSystem];
    
//    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//    self.edgesForExtendedLayout = UIRectEdgeNone;
}

/**
 *  设置navigationBar的显示与隐藏
 *
 *  @param show
 *  @param animated
 */
- (void)showCustomNavigaitonBar:(BOOL)show withFadeAnimation:(BOOL)animated {
    [UIView animateWithDuration:(animated ? 0.2 : 0) animations:^{
        if (show) {
            self.visualEffectView.alpha = 1;
            self.navigationBar.tintColor = CYNaviTitleColor;
            self.navigationBar.titleTextAttributes = [[UINavigationBar appearance] titleTextAttributes];
        } else {
            self.visualEffectView.alpha = 0;
            self.navigationBar.tintColor = [UIColor whiteColor];//
            self.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor clearColor]};
        }
    } completion:^(BOOL finished) {
        [self setNeedsStatusBarAppearanceUpdate];
    }];
}

/**
    Remove custom navigation bar background, and reset to the system default
 */
- (void)transitionFromCustomNavigationBarToSystem {
    [self.visualEffectView removeFromSuperview];
    self.visualEffectView = nil;
    
    // Revert to original values
    [self.navigationBar setBackgroundImage:[[UINavigationBar appearance] backgroundImageForBarMetrics:UIBarMetricsDefault] forBarMetrics:UIBarMetricsDefault];
    [self.navigationBar setTranslucent:[[UINavigationBar appearance] isTranslucent]];
    [self.navigationBar setShadowImage:[[UINavigationBar appearance] shadowImage]];
    [self.navigationBar setTitleTextAttributes:[[UINavigationBar appearance] titleTextAttributes]];
    [self.navigationBar setTintColor:CYNaviTitleColor];
}

- (UIView *)bar {
    if (!_bar) {
        _bar = [[UIView alloc] initWithFrame:self.navigationBar.bounds];
        _bar.backgroundColor = CYNaviThemeColor;
        _bar.y = -20;
        _bar.height = 64;
//        _bar.userInteractionEnabled = YES;
//        [self.navigationBar insertSubview:_bar atIndex:0];
    }
    return _bar;
}

#pragma mark - 返回事件
- (void)setupPopGestureRecognizer {
    if (self.interactivePopGestureRecognizer.enabled == YES) {
        self.interactivePopGestureRecognizer.delegate = self;
    }
}

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem*)item {
    if([self.viewControllers count] < [navigationBar.items count]) {
        return YES;
    }
    
    BOOL shouldPop = YES;
    UIViewController* vc = [self topViewController];
    if([vc respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
        shouldPop = [vc navigationShouldPopOnBackButton];
    }
    
    if(shouldPop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self popViewControllerAnimated:YES];
        });
    } else {
        for(UIView *subview in [navigationBar subviews]) {
            if(subview.alpha < 1.) {
                [UIView animateWithDuration:.25 animations:^{
                    subview.alpha = 1.;
                }];
            }
        }
    }
    return NO;
}
/**
 *  UIGestureRecognizerDelegate
 */
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    UIViewController* vc = [self topViewController];
    if([vc respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
        [vc navigationShouldPopOnBackButton];
    }
    
    if ([gestureRecognizer isEqual:self.interactivePopGestureRecognizer] && [self.viewControllers count]==1) {
        return NO;
    } else {
        return YES;
    }
}
@end
